<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小企业物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996 15899929162
// +----------------------------------------------------------------------
namespace app\common\dao\room;

use app\common\dao\BaseDao;
use app\common\model\room\RoomBasicModel;

class RoomBasicDao extends BaseDao
{

    /**
     * @return RoomBasicModel
     */
    protected function getModel(): string
    {
        return RoomBasicModel::class;
    }

    public function search(array $where, int $propertyId = null)
    {
        return $this->getModel()::getDB()
            ->when($propertyId !== null, function ($query) use ($propertyId) {
                $query->where('property_id', $propertyId);
            })
            ->when(isset($where['contract_id']) && $where['contract_id'] !== '', function ($query) use ($where) {
                $query->where('contract_id', intval($where['contract_id']));
            })
            ->when(isset($where['label_id']) && $where['label_id'] !== '', function ($query) use ($where) {
                $query->whereIn('id', function ($query) use ($where) {
                    $query->name('room_basic_label')->where('label_id', $where['label_id'])->field('room_id');
                });
            })
            ->when(isset($where['status']) && $where['status'] !== '', function ($query) use ($where) {
                if (is_array($where['status'])) {
                    $query->where('status', 'in', $where['status']);
                } else {
                    $query->where('status', (int)$where['status']);
                }
            })
            ->when(isset($where['keywords']) && $where['keywords'] !== '', function ($query) use ($where) {
                $query->whereLike('remark|floor_name|room_name', '%' . trim($where['keywords']) . '%');
            });
    }

    public function roomNameExists(int $propertyId, string $roomName, int $unitId = null, int $except = null)
    {
        return $this->getSearch([])
                ->where('room_name', $roomName)
                ->when($unitId !== null, function ($query) use ($unitId) {
                    $query->where('unit_id', $unitId);
                })
                ->when($propertyId !== null, function ($query) use ($propertyId) {
                    $query->where('property_id', $propertyId);
                })
                ->when($except !== null, function ($query) use ($except) {
                    $query->where('id', '<>', $except);
                })
                ->count() > 0;
    }
}
